divEscapedContentElement = (message)->$('<div/>').text message

divSystemContentElement = (message)->$('<div/>').html "<i>#{message}</i>"

processUserInput = (chatApp, socket)->
  message = $('#send-message').val()
  if message[..0] == '/'
    systemMessage = chatApp.processCommand message
    $('#messages').append divSystemContentElement(systemMessage) if systemMessage
  else
    chatApp.sendMessage($('#room').text(), message)
    $('#messages').append divEscapedContentElement(message)
    .scrollTop $('#messages').prop 'scrollHeight'

  $('#send-message').val ''

socket = io.connect()

$ ()->
  chatApp = new Chat socket
  socket.on 'nameResult', (result)->
    message = if result.success then "You are now known as #{result.name}." else result.message
    $('#messages').append divSystemContentElement(message)

  socket.on 'joinResult', (result)->
    $('#room').text(result.room)
    $('#messages').append divSystemContentElement('Room changed.')

  socket.on 'message', (message)->
    $('#messages').append $('<div/>').text message.text

  socket.on 'rooms', (rooms)->
    $('#room-list').empty()
    console.log "room list=", (room[1..] for room of rooms when room[1..])
    for room of rooms when room[1..]
      $('#room-list').append divEscapedContentElement(room[1..])

#  setInterval (->socket.emit 'rooms'), 1000

  $('#send-message').focus()

  $('#send-form').on 'submit', (e)->
    e.preventDefault()
    e.stopPropagation()
    processUserInput(chatApp, socket)
